const request = require('request');//第三方库
const cheerio = require('cheerio');//第三方库
const iconV = require('iconv-lite');//第三方库
const mkdirp = require('mkdirp');//第三方库
const fs = require('fs');//node自带
const express = require('express');//第三方库
const path = require('path');//node自带
const app = express();//第三方库

var index = 1;


/*创建本地用来保存下载下来的图片目录路径和名称*/
const dir = path.join(__dirname + '/img');

/*使用mkdirp包创建目录*/
mkdirp(dir, function (err) {
    if (err) {
        console.log(err);
    }
});


const option = {
    method: 'get', //请求的方式
    encoding: null,
    url: 'http://desk.zol.com.cn/meinv/1920x1080/1.html'
};

/*保存图片src的数组*/
var arrImg = [];

request(option, function (err, response, body) {
    var $ = cheerio.load(body);
    $('.photo-list-padding a img').each(function () {
        var src = $(this).attr('src');
        arrImg.push(src)
    })
    //遍历保存图片的数组得到图片的src,

    arrImg.map(function (url, index) {
        var url = url.replace(/208x130/, '1920x1200');
        var num = url.lastIndexOf('.') - 2
        var imgName = url.substr(num)
        download(url, imgName, arrImg.length)
    })
});

//下载图片*/
var download = function (url, imgName) {

    request(url).pipe(fs.createWriteStream(dir + '/' + imgName))


};













